import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

// Element Plus
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

// Highlight.js for code syntax highlighting
import hljs from 'highlight.js'
import java from 'highlight.js/lib/languages/java'
import xml from 'highlight.js/lib/languages/xml'
import 'highlight.js/styles/atom-one-dark.css' // Import a theme

// Third-party libraries
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import 'animate.css'

// Custom styles
import './assets/css/global.css'

// Configure dayjs
dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

// Configure NProgress
NProgress.configure({ 
  showSpinner: false,
  easing: 'ease',
  speed: 400
})

// Route transition hooks
router.beforeEach((to, from, next) => {
  NProgress.start()
  
  // 处理权限校验
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const requiresAdmin = to.matched.some(record => record.meta.requiresAdmin)
  
  // 获取用户角色 - 修复：统一使用isAdmin判断而非role属性
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || 'null')
  const isAdmin = userInfo?.isAdmin === 1  // 修改这里，使用isAdmin属性与store保持一致
  
  if (requiresAuth && !isLoggedIn) {
    // 需要登录但未登录，重定向到登录页
    next({ path: '/login', query: { redirect: to.fullPath } })
  } else if (requiresAdmin && !isAdmin) {
    // 需要管理员权限但不是管理员，重定向到首页
    next({ path: '/' })
  } else {
    // 不需要验证，直接进入
    next()
  }
})

router.afterEach(() => {
  NProgress.done()
})

// 忽略ResizeObserver错误，这是UI库的一个常见警告，不会影响功能
const originalConsoleError = window.console.error;
window.console.error = (...args) => {
  if (args[0] && typeof args[0] === 'string' && args[0].includes('ResizeObserver')) {
    // 忽略ResizeObserver相关错误
    return;
  }
  originalConsoleError.apply(console, args);
};

// 添加全局错误处理以忽略ResizeObserver错误
window.addEventListener('error', (event) => {
  if (event.message && event.message.includes('ResizeObserver loop')) {
    event.stopImmediatePropagation();
  }
});

// Create app instance
const app = createApp(App)

// Register global properties
app.config.globalProperties.$dayjs = dayjs
app.config.globalProperties.$hljs = hljs  // Make hljs available to components
app.config.warnHandler = () => {}

// 添加全局代码复制函数
window.copyCode = function(button) {
  // 获取代码块容器
  const codeBlockContainer = button.closest('.code-block-container');
  if (!codeBlockContainer) return;
  
  // 获取代码内容 - 适应新的行结构
  const codeContentElements = codeBlockContainer.querySelectorAll('.line-content');
  if (codeContentElements && codeContentElements.length > 0) {
    const code = Array.from(codeContentElements)
      .map(element => element.textContent || '')
      .join('\n');
    
    // 复制到剪贴板
    navigator.clipboard.writeText(code)
      .then(() => {
        // 显示成功提示
        const messageDiv = document.createElement('div');
        messageDiv.textContent = '代码已复制';
        messageDiv.style.position = 'fixed';
        messageDiv.style.top = '20px';
        messageDiv.style.left = '50%';
        messageDiv.style.transform = 'translateX(-50%)';
        messageDiv.style.backgroundColor = '#67C23A';
        messageDiv.style.color = 'white';
        messageDiv.style.padding = '10px 20px';
        messageDiv.style.borderRadius = '4px';
        messageDiv.style.zIndex = '9999';
        messageDiv.style.boxShadow = '0 2px 12px 0 rgba(0, 0, 0, 0.1)';
        document.body.appendChild(messageDiv);
        
        // 改变按钮状态
        button.innerHTML = '<i class="el-icon-check"></i>';
        button.style.color = '#67C23A';
        
        // 2秒后移除提示
        setTimeout(() => {
          document.body.removeChild(messageDiv);
          button.innerHTML = '<i class="el-icon-document-copy"></i>';
          button.style.color = '';
        }, 2000);
      })
      .catch(err => {
        console.error('复制失败:', err);
        alert('复制失败，请手动复制');
      });
  } else {
    // 回退到旧的方法
    const codeElement = codeBlockContainer.querySelector('code');
    if (!codeElement) return;
    
    const code = codeElement.textContent || '';
    
    // 复制到剪贴板（旧方法）
    navigator.clipboard.writeText(code)
      .then(() => {
        // 显示成功提示
        const messageDiv = document.createElement('div');
        messageDiv.textContent = '代码已复制';
        messageDiv.style.position = 'fixed';
        messageDiv.style.top = '20px';
        messageDiv.style.left = '50%';
        messageDiv.style.transform = 'translateX(-50%)';
        messageDiv.style.backgroundColor = '#67C23A';
        messageDiv.style.color = 'white';
        messageDiv.style.padding = '10px 20px';
        messageDiv.style.borderRadius = '4px';
        messageDiv.style.zIndex = '9999';
        messageDiv.style.boxShadow = '0 2px 12px 0 rgba(0, 0, 0, 0.1)';
        document.body.appendChild(messageDiv);
        
        // 改变按钮状态
        button.innerHTML = '<i class="el-icon-check"></i>';
        button.style.color = '#67C23A';
        
        // 2秒后移除提示
        setTimeout(() => {
          document.body.removeChild(messageDiv);
          button.innerHTML = '<i class="el-icon-document-copy"></i>';
          button.style.color = '';
        }, 2000);
      })
      .catch(err => {
        console.error('复制失败:', err);
        alert('复制失败，请手动复制');
      });
  }
};

// Register plugins
app.use(store)
app.use(router)
app.use(ElementPlus)

// Register all Element Plus icons
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// Register specific languages
hljs.registerLanguage('java', java)
hljs.registerLanguage('xml', xml)

// Enhance Java highlighting by adding custom rules for common Java classes
const javaClassKeywords = [
  'DatatypeConverter', 
  'StandardCharsets', 
  'MessageDigest', 
  'NoSuchAlgorithmException', 
  'SecureRandom'
];

// Add custom highlighting for Java classes
const originalHighlight = hljs.highlight;
hljs.highlight = function(code, options) {
  const result = originalHighlight.call(this, code, options);
  
  if (options.language === 'java') {
    // Add special highlighting for specific Java classes
    javaClassKeywords.forEach(keyword => {
      const pattern = new RegExp(`\\b${keyword}\\b`, 'g');
      result.value = result.value.replace(
        pattern,
        `<span class="hljs-special-class">${keyword}</span>`
      );
    });
  }
  
  return result;
};



// Mount app
app.mount('#app')